package io.gitee.thinkbungee.service;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.pagehelper.PageHelper;
import io.gitee.thinkbungee.dao.GeneratorDao;
import io.gitee.thinkbungee.dao.impl.MongoDBGeneratorDao;
import io.gitee.thinkbungee.factory.MongoDBCollectionFactory;
import io.gitee.thinkbungee.utils.GeneratorUtils;
import io.gitee.thinkbungee.utils.Query;
import io.gitee.thinkbungee.utils.mongo.MongoManager;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.ByteArrayOutputStream;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipOutputStream;

/**
 * 代码生成器
 *
 * @author chenyichang
 * @date 2022/3/8
 */
@Service
public class GeneratorService {

    @Autowired
    private GeneratorDao generatorDao;

    /**
     * 查询所有表
     *
     * @param query 查询条件
     * @return
     */
    public Page queryList(Query query) {
        com.github.pagehelper.Page<?> page = PageHelper.startPage(query.getPage(), query.getLimit());
        List<Map<String, Object>> tableList = generatorDao.queryList(query);
        long total = page.getTotal();
        //如果是mongo计算总量
        if (generatorDao instanceof MongoDBGeneratorDao) {
            total = MongoDBCollectionFactory.getCollectionTotal(query);
        }
        Page<Map<String, Object>> resultPage = new Page<>(query.getPage(), query.getLimit(), total);
        resultPage.setRecords(tableList);
        return resultPage;
    }


    /**
     * 查询指定的表
     *
     * @param tableName 表名
     * @return
     */
    public Map<String, String> queryTable(String tableName) {
        return generatorDao.queryTable(tableName);
    }

    /**
     * 查询表的列名
     *
     * @param tableName 表名
     * @return
     */
    public List<Map<String, String>> queryColumns(String tableName) {
        return generatorDao.queryColumns(tableName);
    }

    /**
     * 生成代码
     *
     * @param tableNames 表名
     * @return
     */
    public byte[] generatorCode(String[] tableNames) {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ZipOutputStream zos = new ZipOutputStream(bos);
        for (String tableName : tableNames) {
            //查询表信息
            Map<String, String> table = queryTable(tableName);
            //查询列信息
            List<Map<String, String>> columns = queryColumns(tableName);
            //生成代码
            GeneratorUtils.generatorCode(table, columns, zos);
        }
        //生成mongo子类的代码
        if (MongoManager.isMongo()) {
            GeneratorUtils.generatorMongoCode(tableNames, zos);
        }
        IOUtils.closeQuietly(zos);
        return bos.toByteArray();
    }
}
